package com.codesal.auditArchiver;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;

public class AuditArchiverActivity extends Activity {
	
	private EditText rxNum;
	private Button addButton;
	private Button contButton;
	private Button removeButton;
	protected ArrayList<String> rxList;
	private ArrayAdapter<String> adapter;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private Uri fileUri;
	private Intent intent;
	private static String fileName;
	private ListView rxListView;
	private String selectedItem;
	static final int DATE_DIALOG_ID = 0;
	private int mYear;
    private int mMonth;
    private int mDay;
    private OnDateSetListener dateSetListener;
    DatePickerDialog dialog;

	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final SaveState data = (SaveState) getLastNonConfigurationInstance();
        if (data != null) {
        	rxNum = data.rxNum;
        	rxList = data.rxList;
            fileName = data.fileName;
        }
        else {
	        rxList = new ArrayList<String>();
	        fileName = "";
        }
        adapter = new ArrayAdapter<String>(this, R.layout.list_element, rxList);
        rxListView = (ListView) findViewById(R.id.list);
        rxListView.setAdapter(adapter);
        

        this.findAllViewsById();
        addButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		if(!rxNum.getText().toString().equals(""))
        			adapter.add(rxNum.getText().toString());
        		rxNum.setText("");
        	}
		});
        contButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		//showDialog(DATE_DIALOG_ID);
        		dialog.show();
        	}
		});
        
        removeButton.setVisibility(View.INVISIBLE);
        
        removeButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		adapter.remove(selectedItem);
        		removeButton.setVisibility(View.INVISIBLE);
        		selectedItem = null;
        	}
		});
        
        rxListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			    // When clicked, show a toast with the TextView text
			    //Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_SHORT).show();
			    view.setSelected(true);
			    removeButton.setVisibility(View.VISIBLE);
			    selectedItem = adapter.getItem(position);	
			}
		});
        
        setCurrentDate();
        dateSetListener = new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker view, int year, 
                                          int monthOfYear, int dayOfMonth) {
                        mYear = year;
                        mMonth = monthOfYear+1; // +1 Because it returns with starting index 0
                        mDay = dayOfMonth;
                        
                        for(int i = 0; i < adapter.getCount(); i++) {
                			if(i != 0)
                				fileName += "_";
                			fileName += adapter.getItem(i);
                		}
                		// create Intent to take a picture and return control to the calling application
                	    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                	    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
                	    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

                	    // start the image capture Intent
                	    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    }
                };
                
                dialog = new DatePickerDialog(this, dateSetListener,mYear, mMonth-1, mDay); //-1 because it uses index starting at 0
		
                
                
    }
    
    @Override
    public Object onRetainNonConfigurationInstance() {
        final SaveState data = new SaveState();
        rxList = new ArrayList<String>();
        
        for(int i = 0; i < adapter.getCount(); i++) {
			rxList.add(adapter.getItem(i));
		}
        data.collectData(rxNum, rxList, fileName);
        return data;
    }
    
    private boolean deleteLastFromDCIM() {

        boolean success = false;
        try {
            File[] images = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "DCIM/Camera").listFiles();
            File latestSavedImage = images[0];
            for (int i = 1; i < images.length; ++i) {
                if (images[i].lastModified() > latestSavedImage.lastModified()) {
                    latestSavedImage = images[i];
                }
            }

            success = latestSavedImage.delete();

            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return success;
        }

    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	if (resultCode == RESULT_OK) {
    		System.out.println(deleteLastFromDCIM());
	    	adapter.clear();
	    	removeButton.setVisibility(View.INVISIBLE);
	    	setCurrentDate();
	    	dialog= new DatePickerDialog(this, dateSetListener,
	                mYear, mMonth-1, mDay); //-1 because it uses index starting at 0
    	}
    	selectedItem = null;
    	fileName = "";
    }
    
    private void findAllViewsById() {
    	rxNum= (EditText) findViewById(R.id.rxNum);
    	addButton = (Button) findViewById(R.id.addButton);
    	contButton = (Button) findViewById(R.id.contButton);
    	removeButton = (Button) findViewById(R.id.removeButton);
    	 
    }
    
    /** Create a file Uri for saving an image or video */
    private Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
    	
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "AuditArchiver");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        File folderPath;
        File mediaFile;
        
        if (type == MEDIA_TYPE_IMAGE){
        	folderPath = new File(mediaStorageDir.getPath() + File.separator + mYear + File.separator + mMonth + File.separator +mDay);
        	
        	if (! folderPath.exists()){
                if (! folderPath.mkdirs()){
                    Log.d("MyCameraApp", "failed to create directory");
                    return null;
                }
            }
        	
            mediaFile = new File(folderPath.getPath() + File.separator +
            fileName + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_"+ fileName + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
    private void setCurrentDate() {
		Calendar calendar = Calendar.getInstance();
		mYear = calendar.get(calendar.YEAR);
		mMonth = (calendar.get(calendar.MONTH)+1);
		mDay = calendar.get(calendar.DAY_OF_MONTH);	
    }
 
}